﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Akabana.Amf.Exception;


#if SILVERLIGHT
using System.IO;
using System.Windows;
using System.Xml;
#endif

namespace Akabana.Amf.Util
{
    public static class AssemblyLoader
    {
        private static IList<Assembly> assemblyList;

        public static Type FindType(string typeName)
        {
            var result = Type.GetType(typeName);
            if (result == null)
            {
                var ass = Assembly.GetExecutingAssembly();
                result = ass.GetType(typeName);
            }
            if (result == null)
            {
                foreach (var assembly in assemblyList)
                {
                    result = assembly.GetType(typeName);
                    if (result != null)
                    {
                        break;
                    }
                }
            }
            if (result == null)
            {
                throw new TypeNotFoundException(typeName);
            }
            return result;
        }

        public static void RegisterAssembly(Assembly assembly)
        {
            assemblyList.Add(assembly);
        }


        public static void Initialize()
        {
            Initialize(null);
        }

        public static void Initialize(Assembly assembly)
        {

            assemblyList = new List<Assembly>();
#if SILVERLIGHT
            if (assembly != null)
            {
                assemblyList.Add(assembly);
            }

            var assemblyPart = new AssemblyPart();
            var xap = new XmlXapResolver();

            Uri uri_;
            foreach (var part in Deployment.Current.Parts)
            {
                uri_ = new Uri(part.Source, UriKind.Relative);
                using (var stream = (Stream)xap.GetEntity(uri_, null, typeof(Stream)))
                {
                    assemblyList.Add(assemblyPart.Load(stream));
                }
            }
#else
            //var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            //assemblyList = new List<Assembly>(assemblies);
#endif
        }

    }
}
